<template>
	<view class="page quotation-add">
		<!-- 基本信息 -->
		<view class="title">基本信息</view>
		<view class="panel">
			<u-form :model="form" ref="uForm" :label-width="210" :error-type="['toast']">
				<u-form-item v-for="(v, k) in fields" :key="k" :label="v.name" :prop="v.fieldName" :required="v.isNull == 1">
					<u-input v-model="form[v.fieldName]" :type="formTypes[v.formType]" :placeholder="v.inputTips" :disabled="v.isDisabled == 1" @click="handlerSelect(v, k)" />
				</u-form-item>
			</u-form>
		</view>

		<!-- 产品清单 -->
		<view class="title">产品清单</view>
		<view class="panel">
			<template v-if="quotationItems.length">
				<view class="deploy-list" v-for="(v, k) in quotationItems" :key="k">
					<o-row class="hd" align="between">
						<o-col span="19">{{ '第' + (k + 1) + '项：' }}{{ v.itemOption }}</o-col>
						<o-col span="5" class="text-right">
							<u-button size="mini" type="primary" @click="relativeQuotation(v, k)">关联产品</u-button>
						</o-col>
					</o-row>
					<template v-if="v.productList.length">
						<u-card v-for="(sv, sk) in v.productList" :key="'card-' + sk">
							<o-row slot="head" class="card-hd">
								<o-col span="22">{{ sk + 1 }}. [{{ sv.productModel }}]{{ sv.productName }}</o-col>
								<o-col span="2" class="text-right">
									<u-icon name="trash" color="#fa3534" size="18px" @click="delProduct(k, sk)"></u-icon>
								</o-col>
							</o-row>
							<view slot="body" class="card-bd">
								<view class="u-field u-border-bottom num">
									<view class="u-field-inner u-label-postion-left">
										<text class="u-label">单价</text>
										<u-number-box :min="1" v-model="sv.productPrice" @change="setProductPrice"></u-number-box>
									</view>
								</view>
								<view class="u-field u-border-bottom num">
									<view class="u-field-inner u-label-postion-left">
										<text class="u-label">数量</text>
										<u-number-box :min="1" v-model="sv.productNumber" @change="setProductPrice"></u-number-box>
									</view>
								</view>
								<u-field label="总价" v-model="sv.totalPrice" :disabled="true"></u-field>
								<u-field label="备注" v-model="sv.remark" placeholder="请输入备注"></u-field>
							</view>
						</u-card>
						<view class="total text-right">
							小计：
							<text style="font-weight: bold">{{ v.subtotal }}</text
							>元
						</view>
					</template>
					<u-empty v-else text="请关联产品"></u-empty>
				</view>
			</template>
			<u-empty v-else text="请选择部署方式"></u-empty>
		</view>

		<!-- 审核信息 -->
		<view class="title">
			审核信息
			<u-tag :text="verifyInfo.examineType === 1 ? '固定审批流' : '授权审批人'" mode="dark" type="warning" shape="circle" size="mini" />
		</view>
		<view class="panel">
			<examine-info :exmine="verifyInfo"></examine-info>
		</view>

		<!-- 按钮 -->
		<view class="footer">
			<u-row class="inner">
				<u-col span="4" class="prices">
					<text class="txt">总计：</text>
					<text class="price">
						<text class="uni">¥</text>
						<text class="num">{{ form.finalSalesPriceTax }}</text>
					</text>
				</u-col>
				<u-col span="8" class="btn">
					<u-button shape="circle" size="medium" type="primary" @click="save(1)">提交审核</u-button>
					<u-button shape="circle" size="medium" type="primary" :plain="true" @click="save(2)">保存草稿</u-button>
					<u-button shape="circle" size="medium" type="info" :plain="true" @click="save(3)">取消</u-button>
				</u-col>
			</u-row>
		</view>

		<!-- 日历组件 -->
		<u-calendar v-model="calendar.status" :mode="calendar.mode" :safe-area-inset-bottom="true" max-date="9999-12-31" @change="calendarChange"></u-calendar>
		<!-- 下啦选择组件 -->
		<u-select v-model="select.status" :list="select.list" @confirm="selectChange"></u-select>
		<!-- 选择客户/商机/关联产品 -->
		<u-popup v-model="popup.status" closeable :mode="popup.mode" :length="popup.height" :safe-area-inset-bottom="true" border-radius="10">
			<component :is="popup.widget" :data="popup.data" @selected="popSelected"></component>
		</u-popup>
	</view>
</template>

<script>
import dayjs from 'dayjs';
import oRow from '@/components/oveui-layout/o-row/o-row.vue';
import oCol from '@/components/oveui-layout/o-col/o-col.vue';
// 客户列表
import listCustomer from '../common/listCustomer';
// 商机列表
import listBusiness from '../common/listBusiness';
// 产品列表
import listProduct from '../common/listProduct';
// 审核信息
import examineInfo from '../common/examineInfo';
import { numberMul } from '@/utils';
export default {
	components: {
		oRow,
		oCol,
		listCustomer,
		listBusiness,
		listProduct,
		examineInfo,
	},
	data: () => ({
		// 当前id
		id: 0,
		// 字段
		fields: [],
		// 审核信息
		verifyInfo: {},
		// 表单相关报价模版
		templates: {},
		// 表单
		form: {
			// 增值税率是否低于13
			reviewRate: 2,
			// 存在价格低于总监价
			reviewPrice: 2,
			// 最终销售价格
			finalSalesPriceTax: 0,
			// 最终总监价格
			finalDirectorPriceTax: 0,
			// 最终结算价格
			finalSettlementPriceTax: 0,
		},
		rules: {},
		// 表单类型对照表
		formTypes: {
			text: 'text',
			date: 'select',
			select: 'select',
			number: 'number',
			customer: 'select',
			business: 'select',
			textarea: 'textarea',
		},
		// 合同标的
		listSubject: [],
		// 产品清单
		quotationItems: [],
		// 当前操作select的字段名称
		curField: '',
		// 当前操作select的索引
		curIndex: -1,
		// 日历组件相关字段
		calendar: {
			status: false,
			mode: 'date',
		},
		// 下啦选择相关字段
		select: {
			status: false,
			list: [],
		},
		// 弹窗信息
		popup: {
			status: false,
			mode: 'bottom',
			height: '600px',
			widget: '',
			// 子组件所需字段
			data: {},
			// 关联产品的index
			index: -1,
		},
		// 关联产品的小记价格
		// productPrice: [],
	}),
	methods: {
		// 获取字段
		async getFields() {
			let data = {
				label: 750,
			};

			// 编辑的时候纯如参数
			this.id > 0 && (data.id = this.id);

			let res = await this.$api.customer.common.fields(data);
			if (res.code === 200) {
				let list = res.data || [];
				this.fields = list;

				list.forEach((v, k) => {
					// 设置表单
					if (this.id > 0) {
						// 编辑回显
						if (v.setting && v.setting.length) {
							this.form[v.fieldName] = v.setting.find((set) => set.value == v.value).name;
							this.fields[k].valueKey = v.value;

							if (v.fieldName === 'quotation_item_id') {
								this.getSubjectList(v.value);
								this.getDeployList(v.value);
							}
						} else {
							if (v.fieldName === 'customer_id') {
								this.form[v.fieldName] = v.value[0].customerName;
								this.fields[k].valueKey = v.value[0].customerId;
							} else if (v.fieldName === 'business_id') {
								this.form[v.fieldName] = '';
							} else {
								this.form[v.fieldName] = v.value || '';
							}
						}
					} else {
						this.form[v.fieldName] = v.value;
					}

					// 设置校验规则
					if (v.isNull == 1 && v.inputTips && (!v.value || v.value.length == 0)) {
						this.rules[v.fieldName] = {
							required: true,
							message: v.inputTips,
							trigger: ['blur', 'change'],
						};
					}
				});

				// 设置日期
				let month = ('0' + (dayjs().month() + 1)).slice(-2);
				let date = ('0' + dayjs().date()).slice(-2);
				this.form.quotation_date = dayjs().year() + '-' + month + '-' + date;
				// 设置发件人信息
				let user = uni.getStorageSync('userInfo');
				this.form.sender_info = '姓名：' + (user.realname || '--') + '；手机：' + (user.mobile || '--') + '；邮箱：' + (user.email || '--') + '；传真：-- ' + '\r\n';
			}
		},
		// 获取审核信息
		async getVerifyInfo() {
			let data = {
				categoryType: 750,
			};
			let res = await this.$api.customer.common.verifyInfo(data);
			if (res.code === 200) {
				this.verifyInfo = res.data || {};
			}
		},
		// 获取表单报价模版
		async getTemplate() {
			let data = {};
			let res = await this.$api.customer.quotation.template(data);
			if (res.code === 200) {
				this.templates = res.data || {};
			}
		},
		// 编辑回显 产品清单
		async getMaterialList() {
			if (!this.id) {
				return;
			}
			let data = {
				quotationId: this.id,
			};
			let res = await this.$api.customer.quotation.materialList(data);
			if (res.code === 200) {
				let list = res.data.listData || [];
				this.quotationItems = list.map((v) => {
					v.productList.map((sv) => {
						sv.directorPrice *= 1;
						sv.productPrice *= 1;
						sv.settlementPrice *= 1;
						return sv;
					});

					return v;
				});
			}
		},
		// 处理select数据
		handlerSelect(row, index) {
			this.curField = row.fieldName;
			this.curIndex = index;

			if (row.formType === 'date') {
				this.calendar.status = true;
			}

			if (row.formType === 'select') {
				// 根据部署方式 获取的 合同标的，提前赋值
				if (row.fieldName === 'subject') {
					// 如果没有选择部署方式
					if (!this.form.quotation_item_id) {
						uni.showToast({
							icon: 'none',
							title: '请选择部署方式',
						});
						return;
					}
					row.setting = this.listSubject;
				}
				if (row.setting && row.setting.length) {
					this.select.list = row.setting.map((v) => {
						v.label = v.name;
						return v;
					});
				}

				row.fieldName !== 'rate' && (this.select.status = true);
			}

			if (row.formType === 'customer') {
				this.popup.widget = 'listCustomer';
				this.popup.data = {};
				this.popup.status = true;
			}

			if (row.formType === 'business') {
				// 如果没有选择客户
				if (!this.form.customer_id) {
					uni.showToast({
						icon: 'none',
						title: '请选择客户',
					});
					return;
				}
				this.popup.data = {
					customerId: this.fields.find((v) => v.fieldName === 'customer_id').valueKey,
				};
				this.popup.widget = 'listBusiness';
				this.popup.status = true;
			}
		},
		// 日历回调
		calendarChange(data) {
			this.form[this.curField] = data.result;
		},
		// 下拉框回调
		selectChange(data) {
			this.form[this.curField] = data[0].label;
			this.fields[this.curIndex].valueKey = data[0].value;

			// 根据部署方式 获取 合同标的、产品清单
			if (this.curField === 'quotation_item_id') {
				this.getSubjectList(data[0].value);
				this.getDeployList(data[0].value);
			}

			// 合同标的选择后，自动填充汇率
			if (this.curField === 'subject') {
				// 筛选rate
				let rate = this.listSubject.filter((v) => v.value === data[0].value)[0].rate;
				this.form.rate = rate;
				// 设置reviewRate信息
				if (rate < 13) {
					this.form.reviewRate = 1;
				} else {
					this.form.reviewRate = 2;
				}
			}
		},
		// pop弹窗回调
		async popSelected(type, data) {
			console.log(data);
			// 客户
			if (type === 'customer') {
				let res = await this.getContacts(data.customerId);
				this.form.customer_info = res;
				this.popup.data = data;

				// 设置表单值
				this.form[this.curField] = data.customerName;
				this.fields[this.curIndex].valueKey = data.customerId;
			}

			// 商机
			if (type === 'business') {
				// 设置表单值
				this.form[this.curField] = data.businessName;
				this.fields[this.curIndex].valueKey = data.businessId;
			}

			// 关联的产品
			if (type === 'product') {
				let productList = [];
				data.forEach((v) => {
					productList.push({
						balance: v.balance,
						productNumber: 1,
						productId: v.productId,
						productModel: v.specName,
						productName: v.name,
						productPrice: Number(v.salesPriceTax), //销售单价
						directorPrice: Number(v.directorPriceTax), //总监单价
						settlementPrice: Number(v.settlementPriceTax), //结算单价
						totalPrice: numberMul(v.productNumber || 1, v.salesPriceTax), //小计/销售总价
						settlementTotalPrice: numberMul(v.productNumber || 1, v.directorPriceTax), //结算总价
						directorTotalPrice: numberMul(v.productNumber || 1, v.settlementPriceTax), //总监总价
					});
				});

				let row = this.quotationItems[this.popup.index].productList;
				if (!row.length) {
					// 添加
					this.quotationItems[this.popup.index].productList.push([...productList]);
				} else {
					// 去重
					productList.forEach((item) => {
						let hasData = row.filter((v) => v.productId == item.productId);
						if (!hasData.length) {
							this.quotationItems[this.popup.index].productList.push(item);
						}
					});
				}
				this.quotationItems[this.popup.index].productList = [...productList];
				this.setProductPrice();
			}

			this.popup.status = false;
		},
		// 获取合同标的、增值税率
		async getSubjectList(val) {
			let data = {
				value: val,
			};
			let res = await this.$api.customer.quotation.subject(data);
			if (res.code === 200) {
				let list = res.data || [];
				this.listSubject = list.map((v) => {
					v.label = v.name;
					return v;
				});
			}
		},
		// 获取产品清单
		async getDeployList(val) {
			let data = {
				deploy: val,
			};
			let res = await this.$api.customer.quotation.deploy(data);
			if (res.code === 200) {
				let list = res.data || [];
				// 这里提前格式化好提交用的字段，在单价和数量更新后，自动更新数据
				if (!this.id) {
					this.quotationItems = [];

					list.forEach((v) => {
						this.quotationItems.push({
							itemOption: v.itemOption,
							quotationItemId: v.quotationItemId,
							rate: v.rate,
							productList: [],
							directorTotalPrice: 0,
							reviewPrice: 2,
							salesTotalPrice: 0,
							settlementTotalPrice: 0,
							subtotal: 0,
						});
					});
				}
			}
		},
		// 根据客户id获取联系信息
		async getContacts(id) {
			let data = {
				customerId: id,
			};
			let res = await this.$api.customer.quotation.customerContacts(data);
			if (res.code === 200) {
				let contacts = '';
				let resData = res.data || {};
				if (resData.list && resData.list.length) {
					resData.list.forEach((v) => {
						contacts += '姓名：' + (v.name || '--') + '；手机：' + (v.mobile || '--') + '；邮箱：' + (v.email || '--') + '；传真：-- ' + '\r\n';
					});
					return contacts;
				}
				return '';
			}
			return '';
		},
		// 关联产品
		relativeQuotation(row, index) {
			this.popup.widget = 'listProduct';
			this.popup.data = row;
			this.popup.status = true;
			this.popup.index = index;
		},
		// 删除产品
		delProduct(index, subIndex) {
			this.quotationItems[index].productList.splice(subIndex, 1);
			this.setProductPrice();
		},
		// 计算关联产品的价格小计
		setProductPrice() {
			let finalSalesPriceTax = 0;
			let finalDirectorPriceTax = 0;
			let finalSettlementPriceTax = 0;

			// 第一遍循环，计算产品相关价格
			this.quotationItems.forEach((v, k) => {
				v.productList.map((sv) => {
					sv.totalPrice = numberMul(sv.productNumber, sv.productPrice); //小计/销售总价
					sv.settlementTotalPrice = numberMul(sv.productNumber, sv.directorPrice); //结算总价
					sv.directorTotalPrice = numberMul(sv.productNumber, sv.settlementPrice); //总监总价

					return sv;
				});
			});

			// 第二遍循环，计算外层价格
			this.quotationItems.map((v) => {
				// 先清空
				v.directorTotalPrice = 0;
				v.salesTotalPrice = 0;
				v.settlementTotalPrice = 0;
				v.subtotal = 0;
				// 再重新计算
				v.productList.forEach((sv) => {
					v.directorTotalPrice += sv.directorTotalPrice;
					v.salesTotalPrice += sv.totalPrice;
					v.settlementTotalPrice += sv.settlementTotalPrice;
					v.subtotal += sv.totalPrice;
				});
				return v;
			});

			// 第三遍循环，计算reviewPrice 和 entity所用的价格信息
			this.quotationItems.map((v) => {
				// 如果单价小于总监价 reviewPrice = 1
				v.reviewPrice = v.salesTotalPrice < v.directorTotalPrice ? 1 : 2;

				// entity所用的价格信息
				finalSalesPriceTax += v.salesTotalPrice;
				finalDirectorPriceTax += v.directorTotalPrice;
				finalSettlementPriceTax += v.settlementTotalPrice;
				return v;
			});
			// 最终销售价格
			this.form.finalSalesPriceTax = finalSalesPriceTax;
			// 最终总监价格
			this.form.finalDirectorPriceTax = finalDirectorPriceTax;
			// 最终结算价格
			this.form.finalSettlementPriceTax = finalSettlementPriceTax;

			this.$forceUpdate();
		},
		// 保存数据
		save(type) {
			if ([1, 2].includes(type)) {
				// 提交审核
				let data = {
					businessInfo: [],
					field: [],
					entity: { ...this.form },
					quotationItems: [...this.quotationItems],
				};
				// 保存草稿
				if (type === 2) {
					data.entity.checkStatus = 5;
				}
				// 如果是编辑带上id
				if (this.id) {
					data.entity.quotationId = this.id;
				}
				// 处理存在field中的下啦选择的值
				this.fields.forEach((v) => {
					if (v.valueKey != null) {
						data.entity[v.fieldName] = v.valueKey;
					}
				});
				data.entity.subject *= 1;

				// 校验
				this.$refs.uForm.validate(async (valid) => {
					if (!valid) {
						return;
					}

					let res = await this.$api.customer.quotation.save(data);
					if (res.code === 200) {
						uni.showToast({
							icon: 'none',
							title: '操作成功',
						});
						// 返回列表
						uni.navigateBack({
							delta: 1,
						});
					}
				});
			}
			if (type == 3) {
				// 取消，返回上一页
				// 返回列表
				uni.navigateBack({
					delta: 1,
				});
			}
		},
	},
	computed: {},
	watch: {},

	// 周期函数--监听页面加载
	onLoad(options) {
		this.id = options.id ? options.id : 0;
	},
	// 周期函数--监听页面初次渲染完成
	onReady() {
		this.$refs.uForm.setRules(this.rules);
	},
	// 周期函数--监听页面显示
	onShow() {
		this.getFields();
		this.getVerifyInfo();
		// this.getTemplate();
		this.getMaterialList();
		if (this.id) {
			uni.setNavigationBarTitle({
				title: '编辑报价清单',
			});
		}
	},
	// 周期函数--监听页面隐藏
	onHide() {},
	// 周期函数--监听页面卸载
	onUnload() {},
	// 页面处理函数--监听用户下拉动作
	onPullDownRefresh() {},
	// 页面处理函数--监听用户上拉触底
	onReachBottom() {},
	// 页面处理函数--监听页面滚动
	/* onPageScroll(event) {}, */
	// 页面处理函数--用户点击右上角分享
	/* onShareAppMessage(options) {}, */
};
</script>

<style lang="scss" scoped>
.page {
	background: #efefef;
}
.mb20 {
	margin-bottom: 20px;
}
.title {
	padding: 15px 15px 10px;
}
.panel {
	background: #fff;
	padding: 15px;

	.deploy-list {
		margin-bottom: 15px;
		&:last-child {
			margin-bottom: 0;
		}

		.hd {
			margin-bottom: 10px;
		}
	}
}

.u-card /deep/ {
	margin: -1px 0 0 0 !important;
	.u-card__head {
		padding: 10px !important;
	}
}

.u-select /deep/ .u-drawer,
.u-drawer {
	z-index: 998 !important;
}
.u-field {
	padding: 10px 14px;
	color: #303133;

	.u-field-inner {
		display: flex;
	}

	.u-label {
		width: 65px;
	}
}

.footer {
	height: 70px;

	.inner {
		position: fixed;
		left: 0;
		right: 0;
		bottom: 0;
		z-index: 10;
		padding: 10px;
		background: #fff;
		box-shadow: 0 0 20px 0 rgba($color: #000000, $alpha: 0.1);

		.prices {
			.price {
				color: #fa3534;
			}
			.num {
				font-size: 20px;
			}
		}

		.btn {
			display: flex;
			text-align: right !important;
			justify-content: flex-end !important;
			.u-btn {
				margin: 0 0 0 10px;
				padding: 0 15px;
			}
		}
	}
}
</style>
